$.prototype.serializeObject = function () {
    var a, o, h, i, e;
    a = this.serializeArray();
    o = {};
    h = o.hasOwnProperty;
    for (i = 0; i < a.length; i++) {
        e = a[i];
        if (!h.call(o, e.name)) {
            o[e.name] = e.value;
        }
    }
    return o;
}

$.extend($.fn, {
    initSelects: function () {
        // 此this 代码所有元素的数姐
        this.each(function (i) {
            // 此this 代表一个元素
            $("").completeOptions(this)
        })
    },

    completeOptions: function (ele, data = {}) {
        data.psize = 10000
        $.ajax({
            url: $(ele).attr("data-url"),
            data: data,
            success: function (res) {
                console.log(res)
                let dft = $(ele).attr("data-dft")

                let genOptions = function (data) {
                    for (let i = 0; i < data.length; i++) {
                        let value = data[i][$(ele).attr("data-value")]
                        let name = data[i][$(ele).attr("data-name")]
                        let option = ""
                        if (dft != "" && value == dft) {
                            option = "<option selected='selected' value='" + value + "'>" + name.replace(/ /g, '&nbsp;') + "</option>"
                        } else {
                            option = "<option value='" + value + "'>" + name.replace(/ /g, '&nbsp;') + "</option>"
                        }
                        $(ele).append(option)
                    }
                }

                if ($(ele).attr("data-dft-option")) {
                    $(ele).append($(ele).attr("data-dft-option"))
                }

                if (res.data.hasOwnProperty('total') && res.data.hasOwnProperty('list')) {
                    genOptions(res.data.list)
                } else {
                    genOptions(res.data)
                }
            },
        })
        console.log(ele)
    },

})

$.ajaxSetup({
    async: true,
    // beforeSend: function (xhr) {
    //     let token = window.localStorage.site_admin_token;
    //     xhr.setRequestHeader("Accept", "application/json");
    //     // xhr.setRequestHeader("Content-Type", "application/json");
    //     xhr.setRequestHeader('Authorization', 'Bearer ' + token);
    // },
    complete: function (xhr, status) {
        if (typeof (xhr.responseJSON) !== "undefined" && xhr.responseJSON.hasOwnProperty("code")) {
            if (typeof (xhr.responseJSON.code) !== "undefined" && xhr.responseJSON.code === 1) {
                showToast(xhr.responseJSON.msg, "/themes/default/entrance/login.html");
            }
        }
        // if (typeof (xhr.responseJSON.code) !== "undefined" && xhr.responseJSON.code === 600) {
        //     showToast(xhr.responseJSON.msg);
        // }
    }
});

function getId() {
    return window.location.hash.substring(1);
}

function getSearchId(name = "id") {
    let searchParams = new URLSearchParams(window.location.search);
    let id = searchParams.get(name);
    if (id == null) {
        return 0;
    }

    return id;
}

function getButton(url, text, type = 'btn-default', attr = '') {
    return '<a class="btn btn-sm ' + type + '" href="' + url + '" ' + attr + ' >' + text + '</a>';
}

function genButtonEdit(url = '') {
    return '<a class="btn btn-sm btn-success" href="' + url + '">编辑</a>';
}

function genButtonDel(url = '') {
    return '<button onclick="ajaxRestDel(this);" class="ajax btn btn-sm btn-danger" href="' + url + '">删除</button>';
}

function ajaxRestDel(element) {
    if (!confirm("确认删除吗？")) {
        return false;
    }

    $.ajax({
        url: $(element).attr('href'),
        method: "DELETE",
        success: function (res) {
            if (res.code == 200){
                showToast("删除成功");
                $(element).parents("tr").remove()
            }
            showToast(res.msg);
        }
    })
}

/**
 * @see https://www.cnblogs.com/RobotTech/p/5737370.html
 * @param element
 */
function logout(element) {
    event.preventDefault();
    // event.stopImmediatePropagation();
    $.ajax({
        url: $(element).attr('href'),
        method: "DELETE",
        success: function (res) {
            if (res.code == 200) {
                window.localStorage.site_admin_token = '';
                showToast("退出成功", "/themes/default/entrance/login.html");
            }
        }
    })
}

/*
@see https://kamranahmed.info/toast#toasts-events
 */
function showToast(msg, url) {
    if ($.toast) {
        $.toast({
            text: msg,
            showHideTransition: 'slide',  // It can be plain, fade or slide
            bgColor: 'blue',              // Background color for toast
            textColor: '#eee',            // text color
            // allowToastClose : false,       // Show the close button or not
            hideAfter: 3000,              // `false` to make it sticky or time in miliseconds to hide after
            stack: 5,                     // `fakse` to show one stack at a time count showing the number of toasts that can be shown at once
            textAlign: 'left',            // Alignment of text i.e. left, right, center
            position: 'top-center',       // bottom-left or bottom-right or bottom-center or top-left or top-right or top-center or mid-center or an object representing the left, right, top, bottom values to position the toast on page
            afterHidden: function () {
                if (url === 'go-back') {
                    window.history.back(-1);
                } else if (url !== undefined) {
                    window.location.href = url;
                }
            }
        })
    } else {
        alert(msg);
        if (url === "undefined") {
            url = "/admin/entrance/login.html";
        }
        setTimeout(function () {
            window.location.href = url;
        }, 500);
    }

}

function initSideBar() {
    $.ajax({
        url: window.location.origin + "/admin-api/v1/sidebar?system_id=1",
        async: true,
        method: 'GET',
        data: $(".ajax-form").serialize(),
        success: function (res) {
            if (res.code === 401) {
                showToast(res.msg, window.location.origin + "/admin/entrance/login.html");
                return;
            }
            // $.get('/dist/js/sideBar.js', function (template) {
            //     $.tmpl(template, res.data).insertAfter('#sidebar-menu');
            // });
            $('#sidebar-level-1').tmpl(res.data.child).insertAfter('#sidebar-menu');

            if (typeof window.sideBarPath === "undefined") {
                window.sideBarPath = window.location.pathname;
            }
            $("a[href='" + window.sideBarPath + "']").find("i").addClass("fa-dot-circle");
            $("a[href='" + window.sideBarPath + "']").parents(".nav-treeview").show();
            $("a[href='" + window.sideBarPath + "']").parents(".has-treeview").addClass("menu-open");
        }
    });
}

function render(info) {
    Object.keys(info).forEach(function (key) {
        if ($("#" + key).length > 0) {
            console.log($("#" + key));
            let ele = $("#" + key)[0].tagName;
            if (ele === "INPUT") {
                $("#" + key).val(info[key]);
                if ($("#" + key).attr("data-image-preview")) {
                    $("#" + key + '-preview').attr('src', info[key]);
                }

                // if($("#" + key)[0].type==="file"){
                //     $("#" + key+'-text').text(info[key]);
                // }else{
                // }
            } else if (ele === "SELECT") {
                $("#" + key).val(info[key]);
                $("#" + key).attr("data-dft", info[key])
                $("#" + key).change();
            } else if (ele === "TEXTAREA") {
                let editorName = $("#" + key).attr('data-editor');
                if (undefined !== editorName) {
                    $('.' + editorName).summernote('code', info[key])
                } else {
                    $("#" + key).val(info[key]);
                }
            } else if (ele === "IMG") {
                $("#" + key).attr('src', info[key]);
            } else {
                $("#" + key).text(info[key]);
            }
        }
    });
}

function ajaxGetInfo(url) {
    $.ajax({
        url: url,
        method: 'GET',
        async: true, // 这个地方设置成false 会导致编辑器上传图片不好用
        success: function (res) {
            render(res.data)
        }
    });
}

function loadContent(url) {
    ajaxGetInfo(url);
}

function loadList(url, callback, data = {}, psize = 10) {
    $('#pagination').pagination({
        dataSource: url,
        alias: {
            pageNumber: 'page',
            pageSize: 'psize',
        },
        pageSize: psize,
        totalNumberLocator: function (response) {
            return response.data.total;
            // return Math.floor(Math.random() * (1000 - 100)) + 100;
        },
        locator: function (response) {
            return 'data.list'
        },
        coping: true,
        homePage: '首页',
        endPage: '末页',
        prevContent: '上页',
        nextContent: '下页',
        ajax: {
            data: data,
            beforeSend: function (xhr) {
                $("#table-body").html('');
                let token = window.localStorage.site_admin_token;
                xhr.setRequestHeader("Accept", "application/json");
                xhr.setRequestHeader("Content-Type", "application/json");
                xhr.setRequestHeader('Authorization', 'Bearer ' + token);
            }
        },
        callback: callback
    });
}

$(document).ready(function () {
    $(".search-now").bind("click", function () {
        let data = $(this).parents("form").serializeObject()
        loadList(sourceUrl, callback, data)
    });

    $("select.auto-complete").initSelects()

    //
    $("select.auto-ref").on("change", function () {
        let key = $(this).attr("data-ref-key") ?? $(this).attr("name")
        let value = $(this).val()
        let ele = document.getElementById($(this).attr("data-ref-ele"))

        $(ele).find("option").remove()

        let data = {}
        data[key] = value
        $("").completeOptions(ele, data)
    })

    if ($('#sidebar-menu').length > 0) {
        initSideBar();
    }

    // ajax form
    //https://www.cnblogs.com/mg007/p/10145582.html
    //https://blog.csdn.net/m0_37505854/article/details/79639046
    //方式1
    if ($.fn.ajaxForm) {
        $("#ajaxFormAdd,.ajaxFormAdd").ajaxForm({
            async: true,
            method: "POST",
            dataType: 'json',
            success: function (res) {
                if (res.code === 200) {
                    showToast(res.msg, 'go-back');
                } else {
                    showToast(res.msg);
                }
            }
        });

        $("#ajaxFormEdit,.ajaxFormEdit").ajaxForm({
            async: true,
            method: "PUT",
            dataType: "JSON",
            beforeSubmit: function (arr, $form, options) {
                options.url += '/' + getSearchId();
            },
            success: function (res) {
                if (res.code === 200) {
                    showToast(res.msg, 'go-back');
                } else {
                    showToast(res.msg);
                }
            }
        });
    }
})